package configs

import (
	"gin-init/pkg/logger"
	"os"
	"path"
	"path/filepath"
	"runtime"
	"strings"

	"github.com/ilyakaznacheev/cleanenv"
	"go.uber.org/zap"
)

const (
	ProjectName = "gin-init"
	ProjectPort = 8080
)

var (
	config      Config
	ProjectPath string
)

type Config struct {
	Environment string           `yaml:"environment"`
	Mysql       map[string]Mysql `yaml:"mysql"`
	Redis       Redis            `yaml:"redis"`
	Timing      Timing           `yaml:"timing"`
	AsyQueue    AsyQueue         `yaml:"asyqueue"`
}

// 初始化
func init() {
	//处理路径问题
	dir, isGoRun, err := GetCurrentPath()
	if err != nil {
		panic(err)
	}
	if isGoRun {
		ProjectPath = filepath.Join(dir, "../")
	} else {
		ProjectPath = dir
	}
	//初始化配置
	config = Config{}
	err = cleanenv.ReadConfig(filepath.FromSlash(ProjectPath+"/.env.yaml"), &config)
	if err != nil {
		panic(err)
	}
	//初始化日志
	logger.Global(logger.NewZap(logger.Config{
		Fields: []zap.Field{
			zap.String("channel", "logger"),
			zap.String("project", ProjectName),
		},
	}))
}

// 获取配置
func Get() *Config {
	return &config
}

// 是否是debug模式
func IsDebug() bool {
	var debug bool
	switch Get().Environment {
	case "development", "dev", "local", "test":
		debug = true
	default:
		debug = false
	}
	return debug
}

// 获取当前路径
func GetCurrentPath() (dir string, isGoRun bool, err error) {
	dir, err = getPathByExecutable()
	if err != nil {
		return
	}

	if strings.Contains(os.Args[0], "GoLand") {
		return getPathByCaller(), true, nil
	}

	tmpDir, _ := filepath.EvalSymlinks(os.TempDir())
	if strings.Contains(dir, tmpDir) {
		return getPathByCaller(), true, nil
	}

	return dir, false, nil
}

// getPathByExecutable 获取当前执行文件绝对路径
func getPathByExecutable() (string, error) {
	exePath, err := os.Executable()
	if err != nil {
		return "", err
	}

	res, _ := filepath.EvalSymlinks(filepath.Dir(exePath))

	return res, nil
}

// getPathByCaller 获取当前执行文件绝对路径（go run）
func getPathByCaller() string {
	var dir string
	_, filename, _, ok := runtime.Caller(2)
	if ok {
		dir = path.Dir(filename)
	}

	return dir
}
